import locationBehavior from '../../../../behaviors/location'
import * as filterConfig from '../../../../models/filter'
import * as transferData from '../../../../models/transferData'
import * as user from '../../../../models/user'
import api from "../../../../common/api"
import {
  dialog
} from '../../../../component/userStatusDialog/control'
const cityMap = require('../../../../utils/city')
const DEFAULT_TIME = '7'
Component({
  behaviors: [locationBehavior],
  /**
   * 组件的属性列表
   */
  lifetimes: {
    attached: function () {},
  },
  properties: {
    salesType: {
      type: String,
      value: 'SUBSCRIBE'
    },
    districtOptions: {
      type: Array,
      value: []
    },
    contentNum: {
      type: Number,
      value: ''
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    usable: true, //当前城市是否开通可用
    subscribe: true, //当前用户是否订阅过
    cityName: '',
    cityCode: '',
    houseType: null, //房源类型
    operated: null, //是否已读
    search: {},
    filterDistrict: {},
    infoTypeCurrent: [],
    filterDistrictOptions: [],
    filterMore: {
      time: DEFAULT_TIME
    },
    vipBool: false, 
    // 快速收索
    quickSearchList: [{
        value: '0',
        label: '未读情报',
      },
      {
        value: '1',
        label: '已读情报',
      },
      {
        value: 'SALES',
        label: '二手',
      },
      {
        value: 'RENT',
        label: '出租',
      }
    ],
    //列表数据
    list_item: [],
    userLat: '', //用户纬度
    userLng: '', //用户经度
    isDue: false, //用户过期时展示提示语
  },
  /**
   * 组件的生命周期
   */
  lifetimes: {
    attached: function () {
      this.initFilterConfig()
      this.isDue()
      this.isSubscribe()
        .then(() => {
          return this.getCurrentCity()
        })
        .then(() => {
          return this.fetchUsable()
        })
        .then(() => {
          this.loadHouse()
        })
    },
  },
  /**
   * 页面的生命周期
   */
  pageLifetimes: {
    show: function () {
      this.refreshCity()
      this.isDue()
      this.isSubscribe()
        .then(() => {
          this.loadHouse()
        })
    },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    // 查询是否有订阅
    isSubscribe() {
      return new Promise((resolve, reject) => {
        api.getOwnerSubscribeResblockCount({}, (res) => {
          if (res && res.data && res.data.isSuccess) {
            if (res.data.content === 0) {
              this.setData({
                subscribe: false
              })
            } else {
              this.setData({
                subscribe: true
              })
            }
            resolve()
          } else {
            reject()
          }
        })
      })
    },
    // 判断当前城市是否开通
    fetchUsable() {
      return new Promise((resolve, reject) => {
        let {
          cityCode
        } = this.data
        api.getOwnerSubscribeCountByCityCode({
          cityCode
        }, (res) => {
          if (res && res.data && res.data.isSuccess) {
            if (res.data.content === 0) {
              this.setData({
                usable: false
              })
            }
            resolve()
          } else {
            reject()
          }
        })
      })
    },
    loadHouse() {
      if (!this.data.usable) return
      if (!this.data.subscribe) return
      this.setData({
        list_item: []
      });
      this.selectComponent("#com-scroll-content").fetchHouse(1, ({
        page,
        pageSize
      }) => {
        return new Promise((resolve, reject) => {
          wx.showLoading({
            title: '加载中...',
          })
          let{
            cityCode,
            houseType,
            operated,
            filterDistrict,
            filterMore,
            userLat, //用户纬度
            userLng, //用户经度
          } = this.data
          let newFilterMore = filterConfig.parseFilter(filterMore)
          api.houseOwnerList({
            pageNum: page,
            pageSize: 10,
            operated,
            areaCode: filterConfig.parseAreaFilter(filterDistrict.district),
            subscribed: true, //是否订阅  不传则为全网   true 我的订阅
            cityCode, //城市编码
            houseType, //房源类型
            bizcircleIdList: filterConfig.parseDistrictFilter(filterDistrict.district), //商圈id
            hdResblockId: this.data.search.hdResblockId, //树懒小区id
            resblockName: this.data.search.resblockName || '',
            areaList: newFilterMore.area, //面积列表
            newExternalTime: newFilterMore.time, //新上时间
            priceList: newFilterMore.price, //价格列表
            rentPriceList: newFilterMore.rentPrice, //出租的价格区间
            shiNumList: newFilterMore.type, //室列表
            nearDistance: newFilterMore.distance, //附近距离
            userLat, //用户纬度
            userLng, //用户经度
          }, ({
            data
          }) => {
            const content = data.content
            data = {
              ...data,
              content: {
                page: content.pageNum,
                rows: content.list,
                total: content.pages
              },
            }
            data.handleData = (rows) => {
              this.setData({
                list_item: this.data.list_item.concat(rows),
              });
              wx.hideLoading()
            };
            resolve(data);
          }, reject);
        });
      });
    },
    // 订阅业主房源
    onClickEmptyBtn() {
      const page = this.getPage()
      page && page.onClickSubscribe()
    },
    getPage() {
      return getCurrentPages() ? getCurrentPages()[getCurrentPages().length - 1] : {}
    },

    // 拿到定义好的筛选项
    initFilterConfig(type) {
      const {
        districtOptions
      } = this.data

      const obj = {
        SALES: {
          id: 'price',
          title: '二手价格区间(万)',
          input: {},
          multi: filterConfig.rangeSalesPriceX
        },
        RENT: {
          id: 'rentPrice',
          title: '出租价格区间(元)',
          input: {},
          multi: filterConfig.rangeRentPriceX
        }
      }

      let jiage;
      if (type) {
        jiage = [obj[type]]
      } else {
        jiage = [obj.SALES, obj.RENT]
      }

      this.setData({
        filterDistrictOptions: [{
          id: 'district',
          cascader: districtOptions
        }],
        filterMoreOptions: [{
            id: 'time',
            title: '时间',
            single: filterConfig.rangeAddTimeX,
            defaultValue: DEFAULT_TIME
          },
          // {
          //   id: 'distance',
          //   title: '距离',
          //   single: filterConfig.rangeDistance //single单选  multi多选
          // },
          ...jiage,
          {
            id: 'area',
            title: '建筑面积',
            input: {},
            multi: filterConfig.rangeArea
          }, {
            id: 'type',
            title: '户型',
            multi: filterConfig.rangeHouseType
          }
        ],
      })
    },
    // 城市筛选
    getCurrentCity() {
      return new Promise((resolve, reject) => {
        this.getCityInfoNew().then(({
          city,
          cityCode
        }) => {
          this.setData({
            cityName: city,
            cityCode: cityCode,
          });

          resolve()
        })
      })
    },
    // 检察城市更新
    refreshCity() {
      let chooseCity = transferData.getData('currentCity')
      transferData.resetData('currentCity')
      if (chooseCity) {
        // this.setData({
        //   cityName: chooseCity.name,
        //   cityCode: chooseCity.code,
        // });
        // this.loadHouse()
        wx.redirectTo({
          url: `/pages/home/propertyOwner/propertyOwner?tab=${this.data.salesType}`,
        })
      }
    },
    // 区域   近30天
    onFilterChange(e) {
      let name = e.currentTarget.dataset.name
      let path = `filter${name}`
      let that = this

      // 选择二手或者出租  展示不一样的
      that.setData({
        infoTypeCurrent: '',
        houseType: ''
      })
      that.initFilterConfig()
      if (e.detail.form.price && e.detail.form.price.length !== 0 && e.detail.form.rentPrice && e.detail.form.rentPrice.length !== 0) {
        console.log('二手和出租都选择了')
      } else {
        if (e.detail.form.price && e.detail.form.price.length !== 0) { //选择了二手
          that.setData({
            infoTypeCurrent: ['SALES'],
            houseType: 'SALES'
          })
          that.initFilterConfig('SALES')
        }
        if (e.detail.form.rentPrice && e.detail.form.rentPrice.length !== 0) { //选择了出租
          that.setData({
            infoTypeCurrent: ['RENT'],
            houseType: 'RENT'
          })
          that.initFilterConfig('RENT')
        }
      }
      // 选择距离时 添加经纬度
      if (e.detail.form.distance) {
        that.getWxLocationBe()
          .then((res) => {
            that.setData({
              userLat: res.latitude, //用户纬度
              userLng: res.longitude, //用户经度
              [path]: e.detail.form
            })
            that.loadHouse()
          })
      } else {
        that.setData({
          [path]: e.detail.form
        })
        that.loadHouse()
      }

    },
    // 收索框的点击事件
    onSearchChange(e) {
      this.setData({
        search: {
          resblockName: e.detail.type === 'key' ? e.detail.value : '',
          hdResblockId: e.detail.type === 'id' ? e.detail.value : '',
        },
      })
      this.clearFilter()
      this.loadHouse()
    },

    clearFilter() {
      this.setData({
        filterMore: {
          time: DEFAULT_TIME
        },
        filterDistrict: {},
      });
      const child = this.selectComponent("#dropdowns");
      child && child.onClear();
    },

    // 快捷筛选
    onInfoTypeChange(e) {
      let arr = e.detail
      let operated = arr.indexOf('1') > -1
      let operatedNot = arr.indexOf('0') > -1
      let sales = arr.indexOf('SALES') > -1
      let rent = arr.indexOf('RENT') > -1
      this.setData({
        infoTypeCurrent: arr,
        operated: ((operated && operatedNot) || (!operated && !operatedNot)) ? null : operated,
        houseType: ((sales && rent) || (!sales && !rent)) ? null : (sales ? 'SALES' : 'RENT')
      })
      this.initFilterConfig(this.data.houseType)
      this.loadHouse()
    },
    // 订阅小区
    _cancelEvent(e) {
      let id = e.detail
      this.isVip('cancelEvent', id, '1')
    },

    // 取消订阅
    _cancelEventX(e) {
      let id = e.detail
      this.isVip('cancelEventX', id, '0')
    },
    // 订阅业主房源
    ownerList() {
      this.isVip('ownerList')
    },
    // 订阅管理
    management() {
      // this.isVip('management')
      wx.navigateTo({
        url: '/pages/home/propertyOwner/com/setting/setting',
      })
    },
    // 判断是不是会员
    isVip(tmp, id, num) {
      user.getVip(true)
        .then(res => {
          if (res == '0') { //会员
            if (tmp == 'management') {
              wx.navigateTo({
                url: '/pages/home/propertyOwner/com/setting/setting',
              })
            }
            if (tmp == 'ownerList') {
              let that = this
              that.checkOfficialAccount()
                .then(() => {
                  wx.navigateTo({
                    url: '/pages/home/propertyOwner/com/select/select',
                  })
                })
                .catch(() => {
                  dialog({
                    dialog: 'allFunctions',
                    confirm: () => {
                      let url = 'https://mp.weixin.qq.com/s/I8sdEESdeHIoKLyYVnDcYQ'
                      wx.navigateTo({
                        url: `/pages/webView/webView?webViewUrl=${url}`
                      })
                    },
                    cancel: () => {
                      wx.showModal({
                        title: '',
                        content: '距离开启业主情报功能只有一步，你是否确定放弃',
                        confirmText: '去完成',
                        cancelText: '残忍放弃',
                        confirmColor: '#F75352',
                        success(res) {
                          if (res.confirm) {
                            let url = 'https://mp.weixin.qq.com/s/I8sdEESdeHIoKLyYVnDcYQ'
                            wx.navigateTo({
                              url: `/pages/webView/webView?webViewUrl=${url}`
                            })
                          }
                        }
                      })
                    }
                  })
                })
            }
          } else {
            dialog({
              dialog: res == '3' ? 'superVip' : 'due',
              confirm: () => {
                wx.navigateTo({
                  url: '/pages/mine/memberCentre/memberCentre'
                })
              }
            })
          }
        })
    },

    // isSubscribe   1订阅小区  0取消订阅
    doSubscribeResblock(id, num) {
      if (num === '0') {
        wx.showLoading({
          title: '取消订阅...',
        })
      } else {
        wx.showLoading({
          title: '订阅中...',
        })
      }
      return new Promise((resolve, reject) => {
        api.doSubscribeResblock({
          hdResblockId: id,
          isSubscribe: num
        }, (res) => {
          if (res && res.data && res.data.isSuccess) {
            wx.hideLoading()
            const {
              list_item
            } = this.data
            let newArr = list_item.filter(item => item.hdResblockId !== id)
            this.setData({
              list_item: newArr
            })
            resolve()
          } else {
            reject()
          }
        })
      })
    },
    // 判断是否关注公众号
    checkOfficialAccount() {
      return new Promise((resolve, reject) => {
        user.getOfficialAccount(true)
          .then(res => {
            if (res === '1') {
              resolve()
            } else {
              reject()
            }
          })
          .catch(() => {
            wx.showToast({
              icon: 'none',
              title: '网络错误，请稍后再试~',
            })
          })
      })
    },


    // 过期时展示提示语
    isDue() {
      user.getVip(true)
        .then(res => {
          this.setData({
            vipBool: res == '0'
          })

          if (res == '2') {
            this.setData({
              isDue: true
            })
          } else {
            this.setData({
              isDue: false
            })
          }
        })
    }
  }
})